//
//  GetBackPasswordVC.m
//  HengYouCai
//
//  Created by ycgwl on 2017/5/1.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "GetBackPasswordVC.h"
#import "SetPasswordVC.h"
#import "NSString+WLString.h"
@interface GetBackPasswordVC ()
@property (nonatomic, retain)UITextField *idCardTF;
@property (nonatomic, retain)UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UILabel *tishi;
@end

@implementation GetBackPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"找回交易密码";

}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self pswSignale];
}
- (void)pswSignale
{
    RACSignal *idCardSignal = [self.idCardTF.rac_textSignal
                            map:^id(NSString *text) {
                                return @([self isValid:text]);
                            }];
    RACSignal *codeSignal = [self.codeTF.rac_textSignal
                            map:^id(NSString *text) {
                                return @([self isValid:text]);
                            }];
    RACSignal *shiMingSignal = [RACSignal combineLatest:@[
                                                          idCardSignal,
                                                          codeSignal
                                                          ]
                                                 reduce:^id(NSNumber *idCard, NSNumber *code) {
                                                     
                                                     return @([idCard boolValue] && [code boolValue]);
                                                 }];
    [shiMingSignal subscribeNext:^(NSNumber*okSignal) {
        if ([okSignal boolValue]) {
            _nextBtn.enabled = YES;
            [_nextBtn setBackgroundColor:Normal_RedColor];
            
        }else{
            _nextBtn.enabled = NO;
            [_nextBtn setBackgroundColor:Normal_UnselecBtnColor];
            
        }
    }];
}

- (BOOL)isValid:(NSString *)str
{
    return str.length>0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PasswordCellID"];
    UILabel *titleLab = [cell viewWithTag:1001];
    UITextField *field = [cell viewWithTag:1002];
    UIButton *btn = [cell viewWithTag:1003];
    [btn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    btn.hidden = indexPath.row==0;
    field.placeholder = indexPath.row==0?@"请输入真实身份证号":@"请输入短信验证码";
    titleLab.text = indexPath.row==0?@"身份证":@"验证码";
    
    if (indexPath.row==0) {
        self.idCardTF = field;
    }else{
        self.codeTF = field;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UITextField *field = [cell viewWithTag:1002];
    
    [field becomeFirstResponder];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y<-130) {
        [self.view endEditing:YES];
        
    }
}

/**
 获取验证码
 */
- (void)getCode:(UIButton *)btn
{
    [self.view endEditing:YES];
    if (_idCardTF.text.length<1) {
        [self.view showHUDWarnTips:@"请输入真实身份证号" hideDelay:1];
        return;
    }
    WLGetWeakSelf(weakself, self);
   
    [HYCNetService accountSendResetPaySmsdWithDict:@{@"idCard":self.idCardTF.text} onSuccess:^(NSDictionary *dictResult) {
        //
        [weakself timmerWith:btn];
        NSString *account = [WLFileManager readUserDataForKey:kUserAccount];
        account = [NSString nameEncryptionWith:account];
        NSString *tishiStr = [NSString stringWithFormat:@"已向手机%@发送短信验证码", account];
        NSMutableAttributedString *tishiAttStr = [[NSMutableAttributedString alloc] initWithString:tishiStr];
        
        [tishiAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"fabc18"] range:NSMakeRange(4, tishiStr.length-7-4)];
        _tishi.attributedText = tishiAttStr;
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        //
        [self.view showHUDWarnTips:errorMsg hideDelay:1];

    }];
}
- (IBAction)next:(id)sender {
    
    [HYCNetService accountVerifyResetPayCodeWithDict:@{@"code":self.codeTF.text} onSuccess:^(NSDictionary *dictResult) {
        //
        SetPasswordVC *VC = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"SetPasswordVCID"];
        VC.isReset = YES;
        [self.navigationController pushViewController:VC animated:YES withHideBottomBarWhenPush:YES pop:YES];
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        //
        [self.view showHUDFailTips:errorMsg hideDelay:1];
    }];
    
}
- (void)timmerWith:(UIButton *)btn
{
    __block int time = 60;
    __block UIButton *verifybutton = btn;
    verifybutton.enabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                verifybutton.backgroundColor = [UIColor colorWithHexString:@"FC740A"];
                [verifybutton setTitle:@"获取验证码" forState:UIControlStateNormal];
                verifybutton.enabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                verifybutton.backgroundColor = [UIColor grayColor];
                NSString *strTime = [NSString stringWithFormat:@"(%d)s",time];
                [verifybutton setTitle:strTime forState:UIControlStateNormal];
                //                verifybutton.titleLabel.textColor = [UIColor whiteColor];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
@end
